$(document).ready(function(){
	initTable();
	App.init();
	$('[data-toggle="popover"]').popover();
});

function initTable(){
	  $('#data_table').bootstrapTable({
      cache: false,
      height: 400,
      striped: true,
      pagination: true,
      pageSize: 10,
      pageList: [10,20,50,100],
      //search: true,
     // showColumns: true,
      //showRefresh: true,
      minimumCountColumns: 1,
      clickToSelect: true,
      queryParams: function (params) {
    	
    	  return params;
      },
      columns: [ {
          field: 'id',
          title: 'ID'
      },{
          field: 'nameZh',
          title: '角色名称'
      },{
          field: 'nameEn',
          title: '角色代码'
      },{
          field: 'description',
          title: '备注'
      },{
          field: 'category',
          title: '分类'
      },{
          field: 'createTime',
          title: '创建时间'
      },{
          field: 'operate',
          title: '操作',
          align: 'center',
          events: operateEvents,
          formatter: operateFormatter
      }]
  });

}



function operateFormatter(value, row, index) {
return ['<a class="permission_edit" href="javascript:void(0)" title="edit">',
        '权限设置',
        '</a>  ',
    '<a class="edit" href="javascript:void(0)" title="edit">',
    '编辑',
    '</a>  '
].join('');
}

window.operateEvents = {
'click .edit': function (e, value, row, index) {
	 setEditParams('editModal',row);
	 $('#editModal').modal('show');
   
},
'click .permission_edit': function (e, value, row, index) {
	
	getRescRoleTreeJSON(row.id,"MENU");//加载与角色关联的菜单
	getRescRoleTreeJSON(row.id,"FUNCTION_POINT");//加载与角色关联的功能点
	setEditRoleId(row.id);
	$('#permissionTreeModal .modal-title').text(row.nameZh+"权限设置");
    $('#permissionTreeModal').modal('show');
}
};
var editRoleId=""
function setEditRoleId(roleId){
	editRoleId=roleId;
}

function setEditParams(containerId,obj){
	   clearEditParams(containerId);
		$("#"+containerId+" input[type='text']").each(function(){
			var attrName=$(this).attr("name");
			$(this).val(obj[attrName]);
		});
		$("#"+containerId+" select").each(function(){
            var attrName=$(this).attr("name");
			$(this).val(obj[attrName]);
		});
	    $("#"+containerId+" input[type='hidden']").each(function(){
            var attrName=$(this).attr("name");
			$(this).val(obj[attrName]);
		});
	   
}

function clearEditParams(containerId){
		$("#"+containerId+" input[type='text']").each(function(){
			$(this).val("");
		});
		$("#"+containerId+" select").each(function(){
			$(this).val("");
		});
	    $("#"+containerId+" input[type='hidden']").each(function(){
	    	$(this).val("");
		});
	    $("#"+containerId+" textarea").each(function(){
	    	$(this).val("");
		});
}

function getParams(containerId){
	var submitData={};
	$("#"+containerId+" input[type='text']").each(function(){
		submitData[$(this).attr("name")]=$(this).val();
	});
	$("#"+containerId+" select").each(function(){
		submitData[$(this).attr("name")]=$(this).val();
	});
	$("#"+containerId+" input[type='hidden']").each(function(){
		submitData[$(this).attr("name")]=$(this).val();
	});
	return submitData;
}


function refreshTable(){
	$('#data_table').bootstrapTable("refresh");
}


function save(){
	var submitData=getParams('addModal');
    $('#addModal').modal('hide');
	$.blockUI({ message:'正在执行操作，请稍等...' });
	$.ajax( {
		url :'core/role/add.htm',
		type : 'post',
		dataType:'json',
		data:submitData,
		success : function(result) {
			 $.unblockUI();
			showAlertModal('注意',result.message);
			if(result.status==1){
				refreshTable();
			}
		},error: function(XMLHttpRequest, textStatus, errorThrown){
		   $.unblockUI();
    	   showAlertModal('注意','系统异常！'+errorThrown);
     }
	});
}

function getRescRoleTreeJSON(roleId,resourcesType){
	var submitData={};
	submitData["roleId"]=roleId;
	submitData["resourcesType"]=resourcesType;
	submitData["roleType"]="ADMIN";
	$.ajax( {
		url :'core/rescrole/getTreeJSON.htm',
		type : 'post',
		dataType:'json',
		data:submitData,
		success : function(result) {
			if(resourcesType=="MENU"){
				initTree(result,"menuTree");
			}else{
				initTree(result,"functionTree");
			}
		},error: function(XMLHttpRequest, textStatus, errorThrown){
    	   showAlertModal('注意','系统异常！'+errorThrown);
     }
	});
}

function initTree(zNodes,treeId){
	var setting = {
			check: {
				enable: true
			},
			data: {
				simpleData: {
					enable: true
				}
			}
		};
	$.fn.zTree.init($("#"+treeId), setting, zNodes);	
	$.fn.zTree.getZTreeObj(treeId).setting.check.chkboxType={ "Y" : "ps", "N" : "ps" };
}


function saveRescRole(treeId,resourcesType){
	var treeObj=$.fn.zTree.getZTreeObj(treeId);
	var nodes=treeObj.getCheckedNodes(true);
	var submitData={};
	submitData["roleId"]=editRoleId;
	submitData["resourcesType"]=resourcesType;
	submitData["roleType"]="ADMIN";
	submitData["resourcesIds"]=getNodesId(nodes).join(",");
	$("#permissionTreeModal").block({ message:'正在执行操作，请稍等...' });
	$.ajax( {
		url :'core/rescrole/save.htm',
		type : 'post',
		dataType:'json',
		data:submitData,
		success : function(result) {
			$("#permissionTreeModal").unblock();
			 $('#permissionTreeModal').modal('hide');
			 showAlertModal('注意',result.message);
		},error: function(XMLHttpRequest, textStatus, errorThrown){
			$.unblockUI();
    	   showAlertModal('注意','系统异常！'+errorThrown);
     }
	});
	
}

function getNodesId(nodes){
	var retVal=new Array();
	for(var i=0;i<nodes.length;i++){
		retVal.push(nodes[i].id);
	}
	return retVal;
}

function update(){
	var submitData=getParams('editModal');
	$('#editModal').modal('hide');
	$.blockUI({ message:'正在执行操作，请稍等...' });
	$.ajax( {
		url :'core/role/update.htm',
		type : 'post',
		dataType:'json',
		data:submitData,
		success : function(result) {
			 $.unblockUI();
			showAlertModal('注意',result.message);
			if(result.status==1){
				refreshTable();
			}
	     },error: function(XMLHttpRequest, textStatus, errorThrown){
	    	 $.unblockUI();
	    	 showAlertModal('注意','系统异常！'+errorThrown);
     }
	});
}

function showAlertModal(title,content){
	$("#alertModal").find('h4').html(title);
	$("#alertModal").find('p').html(content);
	$("#alertModal").modal('show');
}
